package ma.xin.shi;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
//import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
//import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.MessageBox;
//import org.eclipse.swt.custom.ScrolledComposite;

import java.util.ArrayList;
import java.util.List;

import ma.xin.shi.common.MydataTypeInterface;

//import org.eclipse.jface.viewers.ArrayContentProvider;
//import org.eclipse.jface.viewers.CheckboxTableViewer;

import ma.xin.shi.configurations.Service.*;
//import ma.xin.shi.table.TableManager;

public class ServiceDisplay {
	private static Composite dataListComposite; 
	private static Composite workAreaComposite;
	//private static ScrolledComposite RPCWorkContent;
	
	private static Table serviceTable;
	private static Table RPCTable;
	
	private static Text serviceNameText;
	private static Text serviceIdText;
	private static Button confirmButton;             // 确认按钮
	private static AutorsarCommonUtils.ServiceConmfirmButtonSt cfmBtSt;

	// start RPC copmmon view
	//private static Text ServiceNameText;
	private static Text RPCTypeText;
	private static Text RPCName;
	private static Combo RPCSpecificType;
	private static Text RPCMethodID;
	private static Combo RPCProtocol;

	// start RPC Event view
	private static Text EventGroupName;
	private static Text EventGroupID;
	private static Text EventParameter;
	private static Combo SendStrategy;
	private static Text CyclicTime;

	// start field Event view
	//private static Text FieldPropertyName;
	//private static Text FieldPropertyDataType;
	private static Combo getter;
	private static Combo setter;
	private static Combo notifier;
	private static Text setterName;
	private static Text setterID;
	private static Text setterProtocol;
	private static Text getterName;
	private static Text getterID;
	private static Text getterProtocol;
	private static Text notifierName;
	private static Text notifierID;
	private static Text notifierProtocol;

	// input outPut
	private static Text  InputParameter;
	private static Text  OutputParameter;
	private static Combo FireForgotFlag;

	// ECUs point define
	//private static Combo VechileBody, VCC_MCU, VCC_MPU, TMS, VCU, FLZCU, FRZCU, RZCU, ICC, ICC_8155_Android, ICC_8155_QNX;
	//private static Combo TBOX, TBOX_ex, ADCC, LCM, FCM, FLM, OTA, AdvanceService, VDS, TBOXPackage;

	private static CheckableSelectText CstServer;
	private static CheckableSelectText CstClient;
	private static Text serverText;
	private static Text clientText;

	private static AutorsarCommonUtils.ServiceGUISet CurrentViewPage;
	private static String CurrentServiceName;
	private static AutorsarCommonUtils.CurrentRPCType CurrentRPCType;
	
	private static ServiceEventConfig editingEventItem;
	private static ServiceFieldConfig editingFieldItem;
	private static ServiceMethodConfig editingMethodItem;

	public static void display(Composite workArea) {
        for (Control control : workArea.getChildren()) {
            control.dispose();
        }

        addServiceComposite(workArea);
        ServiceListCtrl(dataListComposite);
        cfmBtSt = AutorsarCommonUtils.ServiceConmfirmButtonSt.SERVICE_BT_ADD_SVC;
        ServiceWorkAreaCtrl(workAreaComposite, AutorsarCommonUtils.ServiceGUISet.SERVICE_GUI_LIST);

        workArea.layout(true, true);
    }

	private static void addServiceComposite(Composite parent) {
		// 设置主容器为一行两列的布局
		parent.setLayout(new GridLayout(2, false)); // 两列，不等宽

        // ========== 左侧服务列表区域 ==========
        dataListComposite = new Composite(parent, SWT.BORDER);
        dataListComposite.setLayout(new GridLayout(1, false));
        GridData dataListData = new GridData(SWT.FILL, SWT.FILL, false, true);
        dataListData.widthHint = 200; // 固定宽度
        dataListData.heightHint = 400;
        dataListComposite.setLayoutData(dataListData);
        dataListComposite.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_WHITE));


        // ========== 右侧配置区域 ==========
        workAreaComposite = new Composite(parent, SWT.NULL);
        workAreaComposite.setLayout(new GridLayout(1, false));
        GridData workAreaData = new GridData(SWT.FILL, SWT.FILL, true, true);
        workAreaComposite.setLayoutData(workAreaData);
        workAreaComposite.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
	}
	
	private static void ServiceListCtrl(Composite parent) {
		 for (Control control : parent.getChildren()) {
            control.dispose();
         }

		 ServiceListButtonAdd(parent);
		 ServiceListTableAdd(parent);
	}

	private static void ServiceListButtonAdd(Composite parent) {
	    Composite buttonComposite = new Composite(parent, SWT.NONE);
	    RowLayout rowLayout = new RowLayout(SWT.HORIZONTAL);
	    rowLayout.spacing = 5;
	    buttonComposite.setLayout(rowLayout);

	    GridData buttonData = new GridData(SWT.FILL, SWT.TOP, true, false);
	    buttonComposite.setLayoutData(buttonData);

	    // Add 按钮
	    Button btnAdd = new Button(buttonComposite, SWT.PUSH);
	    btnAdd.setText("Add");

	    // Del 按钮
	    Button btnRemove = new Button(buttonComposite, SWT.PUSH);
	    btnRemove.setText("Del");

	    // Add 按钮：添加新服务
	    btnAdd.addSelectionListener(new SelectionAdapter() {
	        @Override
	        public void widgetSelected(SelectionEvent e) {
	        	cfmBtSt = AutorsarCommonUtils.ServiceConmfirmButtonSt.SERVICE_BT_ADD_SVC;
	            // 清空工作区并显示服务配置界面
	            ServiceWorkAreaCtrl(workAreaComposite, AutorsarCommonUtils.ServiceGUISet.SERVICE_GUI_LIST);
	        }
	    });

	    // Del 按钮：删除表格中选中的服务
	    btnRemove.addSelectionListener(new SelectionAdapter() {
	        @Override
	        public void widgetSelected(SelectionEvent e) {
	            int selectedIndex = serviceTable.getSelectionIndex();
	            if (selectedIndex != -1) {
	                TableItem selectedItem = serviceTable.getItem(selectedIndex);
	                String serviceName = selectedItem.getText(1);  // 获取服务名

	                boolean success = ConfigurationManager.getInstance()
	                        .getServiceConfig()
	                        .removeService(serviceName);
	                if (success) {
	                    serviceTable.remove(selectedIndex);
	                    refreshTableIndex();
	                } else {
	                	Shell shell = parent.getShell();
	                    MessageBox dialog = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
	                    dialog.setText("Error");
	                    dialog.setMessage("Can not delete Service [" + serviceName + "]");
	                    dialog.open();
	                }
	            }
	        }
	    });
	}

	private static void refreshTableIndex() {
	    TableItem[] items = serviceTable.getItems();
	    for (int i = 0; i < items.length; i++) {
	        items[i].setText(0, String.valueOf(i + 1));
	    }
	}

	private static void ServiceListTableAdd(Composite parent) {
	    // 创建表格控件
	    serviceTable = new Table(parent, SWT.BORDER | SWT.FULL_SELECTION);
	    serviceTable.setHeaderVisible(true);  // 显示表头
	    serviceTable.setLinesVisible(true);   // 显示表格线

	    // 设置布局数据：占满父容器剩余空间
	    GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
	    serviceTable.setLayoutData(gridData);

	    // 添加两列：Index 和 ServiceName
	    TableColumn indexColumn = new TableColumn(serviceTable, SWT.NONE);
	    indexColumn.setText("Index");
	    indexColumn.setWidth(50);  // 设置宽度

	    TableColumn nameColumn = new TableColumn(serviceTable, SWT.NONE);
	    nameColumn.setText("ServiceName");
	    nameColumn.setWidth(150);  // 设置宽度

	    loadExistingServiceToTable(); //加载当前已经配置的所有Service数据

	    // ===== 添加监听器开始 =====
	    serviceTable.addListener(SWT.Selection, e -> {
	        if (serviceTable.getSelectionCount() > 0) {
	            TableItem selectedItem = serviceTable.getSelection()[0];
	            String serviceName = selectedItem.getText(1); // 第2列是服务名
	            
	            CurrentServiceName = serviceName;
	            AutorsarCommonUtils.logEx("clicked: " + serviceName);
	            cfmBtSt = AutorsarCommonUtils.ServiceConmfirmButtonSt.SERVICE_BT_SAVE_SVC;
	            ServiceWorkAreaCtrl(workAreaComposite, AutorsarCommonUtils.ServiceGUISet.SERVICE_GUI_LIST);	            
	            
	            // 获取服务对象
	            ServiceEntry entry = ConfigurationManager.getInstance().getServiceConfig().getServiceByName(serviceName);
	            if (entry != null) {
	                // 设置到右侧输入框
	                serviceNameText.setText(entry.getServiceName());
	                serviceIdText.setText(String.format("0x%X", entry.getServiceId()));
	            }
	        }
	    });

	    // 双击事件
	    serviceTable.addListener(SWT.DefaultSelection, e -> {
	        if (serviceTable.getSelectionCount() > 0) {
	            TableItem selectedItem = serviceTable.getSelection()[0];
	            String serviceName = selectedItem.getText(1);
	            
	            CurrentServiceName = serviceName;
	            AutorsarCommonUtils.logEx("Double clicked: " + serviceName);
	            cfmBtSt = AutorsarCommonUtils.ServiceConmfirmButtonSt.SERVICE_BT_ADD_RPC;
	            ServiceWorkAreaCtrl(workAreaComposite, AutorsarCommonUtils.ServiceGUISet.SERVICE_GUI_EVENT);
	            
	            ServiceEntry entry = ConfigurationManager.getInstance().getServiceConfig().getServiceByName(serviceName);
	            if (entry != null) {
	            	loadServiceRpcDetails(serviceName, CurrentViewPage);
	            }
	        }
	    });
	    // ===== 添加监听器结束 =====
	}
	
	public static void loadServiceRpcDetails(String serviceName, AutorsarCommonUtils.ServiceGUISet viewType) {
	    ServiceEntry service = ConfigurationManager.getInstance()
	            .getServiceConfig()
	            .getServiceByName(serviceName);

	    if (service == null) return;

	    if (RPCTable != null && RPCTable.getItems() != null) {
	        for (TableItem item : RPCTable.getItems()) {
	            item.dispose();
	        }
	    }
	    AutorsarCommonUtils.logEx("in loadServiceRpcDetails viewType: \n" +viewType);
	    switch (viewType) {
	        case SERVICE_GUI_LIST:
	        	AutorsarCommonUtils.logEx("Wrong GUI < not RPC View>");
	            break;
	        case SERVICE_GUI_EVENT:
	        	loadEventlistToTable(service);
	            break;
	        case SERVICE_GUI_FIELD:
	        	loadFieldlistToTable(service);
	            break;
	        case SERVICE_GUI_METHOD:
	        	loadMethodlistToTable(service);
	            break;
	    }
	}

	private static void loadEventlistToTable(ServiceEntry service) {
		AutorsarCommonUtils.logEx("start load SERVICE_GUI_EVENT");
        List<ServiceEventConfig> allEvents = service.getEvents();
        if (allEvents != null && !allEvents.isEmpty()) {
            int i = 0;
            for (ServiceEventConfig event : allEvents) {
                TableItem item = new TableItem(RPCTable, SWT.NONE);
                item.setText(new String[]{
                    String.valueOf(i++),
                    event.getEventName(),
                    Integer.toHexString(event.getEventId()).toUpperCase()
                });
                item.setData(event); // 绑定当前 event 对象
            }
        }
	}

	private static void loadFieldlistToTable(ServiceEntry service) {
		AutorsarCommonUtils.logEx("start load SERVICE_GUI_FIELD");
        List<ServiceFieldConfig> allFields = service.getFields();
        if (allFields != null && !allFields.isEmpty()) {
            int i = 0;
            for (ServiceFieldConfig Field : allFields) {
                TableItem item = new TableItem(RPCTable, SWT.NONE);
                item.setText(new String[]{
                    String.valueOf(i++),
                    Field.getFieldName(),
                    Integer.toHexString(Field.getFieldId()).toUpperCase()
                });
                item.setData(Field); // 绑定当前 event 对象
            }
        }
	}

	private static void loadMethodlistToTable(ServiceEntry service) {
		AutorsarCommonUtils.logEx("start load SERVICE_GUI_METHOD");
        List<ServiceMethodConfig> allMethods = service.getMethods();
        if (allMethods != null && !allMethods.isEmpty()) {
            int i = 0;
            for (ServiceMethodConfig Method : allMethods) {
                TableItem item = new TableItem(RPCTable, SWT.NONE);
                item.setText(new String[]{
                    String.valueOf(i++),
                    Method.getMethodName(),
                    Integer.toHexString(Method.getMethodId()).toUpperCase()
                });
                item.setData(Method); // 绑定当前 event 对象
            }
        }
	}

	// 方法定义时要给枚举参数一个变量名，比如叫 viewType
	private static void ServiceWorkAreaCtrl(Composite parent, AutorsarCommonUtils.ServiceGUISet viewType) {
	    for (Control control : parent.getChildren()) {
	        control.dispose();
	    }
	    CurrentViewPage = viewType;
	    Label placeholder = new Label(parent, SWT.CENTER);
	    placeholder.setText("【loading...】");

	    switch (viewType) {
	        case SERVICE_GUI_LIST:
	            ServiceViewList(parent); 
	            break;
	        case SERVICE_GUI_EVENT:
	        case SERVICE_GUI_FIELD:
	        case SERVICE_GUI_METHOD:
	        	ServiceViewRPC(parent);
	        	break;
	    }

	    parent.layout(true, true);
	}

	private static void ServiceViewList(Composite parent) {
		for (Control control : parent.getChildren()) {
	        control.dispose();
	    }
		
		// 设置主容器为 GridLayout，2列，自动扩展行数
        parent.setLayout(new GridLayout(2, false));

        // 创建所有 Label + Text 表单项
        serviceNameText = createLabeledText(parent, "Service Name:");
        serviceIdText = createLabeledText(parent, "Service ID:");
        
        if (null == serviceNameText) {
        	AutorsarCommonUtils.logEx("serviceNameText is Null");
        }
        
        if (null == serviceIdText) {
        	AutorsarCommonUtils.logEx("serviceIdText is Null");
        }
        
        // add button
        ServiceConfirmButtonAdd(parent);
	}
	
	private static void ServiceViewRPC(Composite parent) {
		for (Control control : parent.getChildren()) {
	        control.dispose();
	    }

		Composite[] composites = addRPCViewComposite(parent);
		CTabFolder tabFolder = (CTabFolder) composites[1];
        Composite RPCListComposite = composites[0];
        Composite workContent = composites[2];

        // add Tabs
        addTabToFolder(tabFolder, "Event", RPCListComposite, workContent);
        addTabToFolder(tabFolder, "Field", RPCListComposite, workContent);
        addTabToFolder(tabFolder, "Method", RPCListComposite, workContent);

        // 设置默认加载第一个 Tab 的内容
        //if (tabFolder.getItemCount() > 0) {
        //    String defaultTabName = tabFolder.getItem(0).getText();
        //    RPCdataListAreaCtrl(RPCListComposite, defaultTabName);
        //    ServiceRPCWorkContentCtrl(workContent, defaultTabName);
        //}
        // 使用监听的方式初始化页面， 设置初始显示Event页面
        String defaultTabName = "Event";  // 固定默认 Tab 名称
	    selectTabByName(tabFolder, defaultTabName); // 模拟选择
	    handleRpcTabSelection(RPCListComposite, workContent, defaultTabName); // 触发加载
	    tabFolder.setSelection(tabFolder.getItem(0)); // 可视上高亮第一个 Tab

        // 监听 Tab 切换事件
        tabFolder.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
				confirmButton.setText("Add");
		        cfmBtSt = AutorsarCommonUtils.ServiceConmfirmButtonSt.SERVICE_BT_ADD_RPC;
			
                CTabItem selectedTab = tabFolder.getSelection();
                String selectedTabName = selectedTab.getText();
                AutorsarCommonUtils.logEx("in ServiceViewRPC selectedTabName 222--: " +selectedTabName);
                CurrentRPCType = ConvertRPCTabName2Enum(selectedTabName);
                CurrentViewPage = conventRPCTypeToGUIView(CurrentRPCType);
                AutorsarCommonUtils.logEx("in ServiceViewRPC CurrentRPCType 333--: " +CurrentRPCType);
                AutorsarCommonUtils.logEx("in ServiceViewRPC CurrentViewPage 444--: " +CurrentViewPage);
                RPCdataListAreaCtrl(RPCListComposite, selectedTabName);
                ServiceRPCWorkContentCtrl(workContent, selectedTabName);
                
                ServiceEntry entry = ConfigurationManager.getInstance().getServiceConfig().getServiceByName(CurrentServiceName);
	            if (entry != null) {
	            	AutorsarCommonUtils.logEx("in ServiceViewRPC CurrentRPCType--: " +CurrentRPCType);
	            	AutorsarCommonUtils.logEx("in ServiceViewRPC CurrentViewPage--: " +CurrentViewPage);
	            	loadServiceRpcDetails(CurrentServiceName, CurrentViewPage);
	            }
            }
        });
	}
	
	private static AutorsarCommonUtils.ServiceGUISet conventRPCTypeToGUIView(AutorsarCommonUtils.CurrentRPCType rpcType) {
		AutorsarCommonUtils.ServiceGUISet GuiView;
		AutorsarCommonUtils.logEx("in conventRPCTypeToGUIView rpcType 555--: " +rpcType);
        
		switch (rpcType) {
			case AutorsarCommonUtils.CurrentRPCType.CurrentRPCEvent:
				GuiView = AutorsarCommonUtils.ServiceGUISet.SERVICE_GUI_EVENT;
				break;
			case AutorsarCommonUtils.CurrentRPCType.CurrentRPCField:
				GuiView = AutorsarCommonUtils.ServiceGUISet.SERVICE_GUI_FIELD;
				break;
			case AutorsarCommonUtils.CurrentRPCType.CurrentRPCMethod:
				GuiView = AutorsarCommonUtils.ServiceGUISet.SERVICE_GUI_METHOD;
				break;
			default: GuiView = AutorsarCommonUtils.ServiceGUISet.SERVICE_GUI_EVENT;
				break;
		}
		AutorsarCommonUtils.logEx("in conventRPCTypeToGUIView GuiView 666--: " +GuiView);
		return GuiView;
	}
	
	private static void handleRpcTabSelection(Composite rpcListComposite, Composite workContent, String tabName) {
	    RPCdataListAreaCtrl(rpcListComposite, tabName);
	    ServiceRPCWorkContentCtrl(workContent, tabName);
	}

	private static void selectTabByName(CTabFolder tabFolder, String tabName) {
	    for (CTabItem item : tabFolder.getItems()) {
	        if (tabName.equals(item.getText())) {
	            tabFolder.setSelection(item);
	            break;
	        }
	    }
	}

	private static AutorsarCommonUtils.CurrentRPCType ConvertRPCTabName2Enum(String name) {
		AutorsarCommonUtils.CurrentRPCType currType = AutorsarCommonUtils.CurrentRPCType.CurrentRPCEvent;
		switch (name) {
		case "Event":
			currType = AutorsarCommonUtils.CurrentRPCType.CurrentRPCEvent;
			break;
		case "Field":
			currType = AutorsarCommonUtils.CurrentRPCType.CurrentRPCField;
			break;
		case "Method":
			currType = AutorsarCommonUtils.CurrentRPCType.CurrentRPCMethod;
			break;
		}
		
		return currType;
	}
	
	private static void RPCdataListAreaCtrl(Composite parent, String selectedTabName)
	{
		for (Control child : parent.getChildren()) {
	        child.dispose();
	    }

		// add data List button [Add, Del]
	    addServiceRPCListButton(parent);
	    // add data list table
	    addServiceRPCListTable(parent);
	
		parent.layout();
	}
	
	private static void ServiceRPCWorkContentCtrl(Composite parent, String selectedTabName)
	{
		for (Control child : parent.getChildren()) {
	        child.dispose();
	    }
		
		System.out.print("---in ServiceRPCWorkContentCtrl, selectedTabName: \n" +selectedTabName);
		
		parent.setLayout(new GridLayout(2, false));
		
		if ("Event".equals(selectedTabName)) {
			ServiceRPCEventCtrl(parent);
	    } else if ("Field".equals(selectedTabName)) {
	    	ServiceRPCFieldCtrl(parent);
	    } else if ("Method".equals(selectedTabName)) {
	    	ServiceRPCMethodCtrl(parent);
	    } else {
	    	;
	    }

		// add button
        ServiceConfirmButtonAdd(parent);
		parent.layout(true, true);
	}

	private static void ServiceRPCEventCtrl(Composite parent) {		
		String[] SendStrategyList =  {"cyclic", "update on change"};

		// add Service common view
		ServiceRPCCommonView(parent, "Event");

		EventGroupName = AutorsarCommonUtils.createLabeledText(parent, "Event Group Name");
		EventGroupID   = AutorsarCommonUtils.createLabeledText(parent, "Event Group ID");
		EventParameter = AutorsarCommonUtils.createLabeledText(parent, "Event Parameter");
		SendStrategy   = AutorsarCommonUtils.createLabeledCombo(parent, "Send Strategy", SendStrategyList);
		CyclicTime     = AutorsarCommonUtils.createLabeledText(parent, "Cyclic Time");

		// add ECU C\S view
		AddECUsEndpointView(parent);

		// 添加表格选择监听器
		RPCTable.addSelectionListener(new SelectionAdapter() {
		    @Override
		    public void widgetSelected(SelectionEvent e) {
		        TableItem selectedItem = (TableItem) e.item;
		        AutorsarCommonUtils.logEx("Listen Event RPC click");

		        if (selectedItem == null) {
		            AutorsarCommonUtils.logEx("❌ 选中项为空");
		            return;
		        }

		        Object data = selectedItem.getData();
		        if (data == null) {
		            AutorsarCommonUtils.logEx("❌ 该项未绑定任何数据");
		            return;
		        }

		        if (data instanceof ServiceEventConfig) {
		        	
		        	confirmButton.setText("Save");
		        	cfmBtSt = AutorsarCommonUtils.ServiceConmfirmButtonSt.SERVICE_BT_SAVE_RPC;

		            ServiceEventConfig config = (ServiceEventConfig) data;
		            editingEventItem = config;
		            AutorsarCommonUtils.logEx("editingEventItem is: " + config.getEventName());
		            AutorsarCommonUtils.setSafeText(RPCName, config.getEventName());
		            AutorsarCommonUtils.setSafeText(RPCMethodID, Integer.toString(config.getEventId()));
					AutorsarCommonUtils.setSafeCombo(RPCSpecificType, config.getRPCSpecificType());
					AutorsarCommonUtils.setSafeCombo(RPCProtocol, config.getRPCProtocol());
					AutorsarCommonUtils.setSafeText(EventGroupName, config.getGroupName());
					//EventGroupID.setText(Integer.toHexString(config.getGroupId()).toUpperCase());
					//EventGroupID.setText(String.format("0x%X", config.getGroupId()));
					AutorsarCommonUtils.setSafeText(EventGroupID, Integer.toString(config.getGroupId()));
				    AutorsarCommonUtils.setSafeText(EventParameter, config.getEventPara());
				    AutorsarCommonUtils.setSafeCombo(SendStrategy, config.getSendStrategy());
				    AutorsarCommonUtils.setSafeText(CyclicTime, config.getCyclicTime());
					CstServer.setSelectedItems(config.getsList() != null ? config.getsList().toArray(new String[0]) : new String[0]);
					CstClient.setSelectedItems(config.getcList() != null ? config.getcList().toArray(new String[0]) : new String[0]);
		        } else {
		            AutorsarCommonUtils.logEx("数据类型错误：" + data.getClass());
		        }
		    }
		});
	}

	private static void ServiceRPCFieldCtrl(Composite parent) {
		String[] status =  {"false","true"};
		// add Service common view
		ServiceRPCCommonView(parent, "Field");

		// field
		//FieldPropertyName = AutorsarCommonUtils.createLabeledText(parent, "Field Property Name");
		//FieldPropertyDataType   = AutorsarCommonUtils.createLabeledText(parent, "Field Property Data Type");
		getter = AutorsarCommonUtils.createLabeledCombo(parent, "Getter-Has", status);
		setter = AutorsarCommonUtils.createLabeledCombo(parent, "Setter-Has", status);
		notifier = AutorsarCommonUtils.createLabeledCombo(parent, "Notifier-Has", status);

		setterName = AutorsarCommonUtils.createLabeledText(parent, "setterName");
		setterID = AutorsarCommonUtils.createLabeledText(parent, "setterID");
		setterProtocol = AutorsarCommonUtils.createLabeledText(parent, "setterProtocol");

		getterName = AutorsarCommonUtils.createLabeledText(parent, "getterName");
		getterID = AutorsarCommonUtils.createLabeledText(parent, "getterID");
		getterProtocol = AutorsarCommonUtils.createLabeledText(parent, "getterProtocol");

		notifierName = AutorsarCommonUtils.createLabeledText(parent, "notifierName");
		notifierID = AutorsarCommonUtils.createLabeledText(parent, "notifierID");
		notifierProtocol = AutorsarCommonUtils.createLabeledText(parent, "notifierProtocol");

		// if RPCSpecificType is event then need add:
		EventGroupName = AutorsarCommonUtils.createLabeledText(parent, "Event Group Name");
		EventGroupID   = AutorsarCommonUtils.createLabeledText(parent, "Event Group ID");
		EventParameter = AutorsarCommonUtils.createLabeledText(parent, "Event Parameter");

		// add ECU C\S view
		AddECUsEndpointView(parent);

		// 添加表格选择监听器
		RPCTable.addSelectionListener(new SelectionAdapter() {
		    @Override
		    public void widgetSelected(SelectionEvent e) {
		        TableItem selectedItem = (TableItem) e.item;
		        AutorsarCommonUtils.logEx("Listen Field RPC click");

		        if (selectedItem == null) {
		            AutorsarCommonUtils.logEx("❌ 选中项为空");
		            return;
		        }

		        Object data = selectedItem.getData();
		        if (data == null) {
		            AutorsarCommonUtils.logEx("❌ 该项未绑定任何数据");
		            return;
		        }

		        if (data instanceof ServiceFieldConfig) {
		        	confirmButton.setText("Save");
		        	cfmBtSt = AutorsarCommonUtils.ServiceConmfirmButtonSt.SERVICE_BT_SAVE_RPC;
		        	
		        	ServiceFieldConfig config = (ServiceFieldConfig) data;
		            editingFieldItem = config;
		            AutorsarCommonUtils.logEx("editingFieldItem is: " + config.getFieldName());
		            RPCName.setText(config.getFieldName());
		            RPCMethodID.setText(String.valueOf(config.getFieldId()));
					RPCSpecificType.setText(config.getRPCSpecificType());
					RPCProtocol.setText(config.getRPCProtocol());

					//FieldPropertyName.setText(config.getPropertyName());
					//FieldPropertyDataType.setText(config.getPropertyDataType());
					EventGroupName.setText(config.getGroupName());
					//EventGroupID.setText(Integer.toHexString(config.getGroupId()).toUpperCase());
					EventGroupID.setText(String.format("0x%X", config.getGroupId()));
					EventParameter.setText(config.getEventPara());
					//getter.setText(AutorsarCommonUtils.booleanToString(config.getGetterStatus()));
					//setter.setText(AutorsarCommonUtils.booleanToString(config.getSetterStatus()));
					//notifier.setText(AutorsarCommonUtils.booleanToString(config.getNotifierStatus()));
					AutorsarCommonUtils.setSafeCombo(getter, AutorsarCommonUtils.booleanToString(config.getGetterStatus()));
					AutorsarCommonUtils.setSafeCombo(setter, AutorsarCommonUtils.booleanToString(config.getSetterStatus()));
					AutorsarCommonUtils.setSafeCombo(notifier, AutorsarCommonUtils.booleanToString(config.getNotifierStatus()));

					AutorsarCommonUtils.setSafeText(getterName, config.getGetterName());
					AutorsarCommonUtils.setSafeText(getterID, config.getGetterID());
					AutorsarCommonUtils.setSafeText(getterProtocol, config.getGetterProtocol());
					AutorsarCommonUtils.setSafeText(setterName, config.getSetterName());
					AutorsarCommonUtils.setSafeText(setterID, config.getSetterID());
					AutorsarCommonUtils.setSafeText(setterProtocol, config.getSetterProtocol());
					AutorsarCommonUtils.setSafeText(notifierName, config.getNotifierName());
					AutorsarCommonUtils.setSafeText(notifierID, config.getNotifierID());
					AutorsarCommonUtils.setSafeText(notifierProtocol, config.getNotifierProtocol());

					AutorsarCommonUtils.setSafeText(RPCName, config.getSetterName());

					CstServer.setSelectedItems(config.getsList() != null ? config.getsList().toArray(new String[0]) : new String[0]);
					CstClient.setSelectedItems(config.getcList() != null ? config.getcList().toArray(new String[0]) : new String[0]);
		        } else {
		            AutorsarCommonUtils.logEx("数据类型错误：" + data.getClass());
		        }
		    }
		});
	}

	private static void ServiceRPCMethodCtrl(Composite parent) {
		String[] FireForgotflagList =  {"YES", "NO"};

		// add Service common view
		ServiceRPCCommonView(parent, "Method");

		InputParameter = AutorsarCommonUtils.createLabeledText(parent, "InputParameter");
		OutputParameter   = AutorsarCommonUtils.createLabeledText(parent, "OutputParameter");
		FireForgotFlag = AutorsarCommonUtils.createLabeledCombo(parent, "Fire Forgot Flag", FireForgotflagList);

		// add ECU C\S view
		AddECUsEndpointView(parent);

		// 添加表格选择监听器
		RPCTable.addSelectionListener(new SelectionAdapter() {
		    @Override
		    public void widgetSelected(SelectionEvent e) {
		        TableItem selectedItem = (TableItem) e.item;
		        AutorsarCommonUtils.logEx("Listen Method RPC click");

		        if (selectedItem == null) {
		        	AutorsarCommonUtils.logEx("❌ 选中项为空");
		            return;
		        }

		        Object data = selectedItem.getData();
		        if (data == null) {
		        	AutorsarCommonUtils.logEx("❌ 该项未绑定任何数据");
		            return;
		        }

		        if (data instanceof ServiceMethodConfig) {
		        	confirmButton.setText("Save");
		        	cfmBtSt = AutorsarCommonUtils.ServiceConmfirmButtonSt.SERVICE_BT_SAVE_RPC;

		        	ServiceMethodConfig config = (ServiceMethodConfig) data;
		            editingMethodItem = config;
		            AutorsarCommonUtils.logEx("editingMethodItem is: " + config.getMethodName());
		            AutorsarCommonUtils.setSafeText(RPCName, config.getMethodName());
		            AutorsarCommonUtils.setSafeText(RPCMethodID, MydataTypeInterface.safeIntToString(config.getMethodId(), ""));
					AutorsarCommonUtils.setSafeCombo(RPCSpecificType, config.getRPCSpecificType());
					AutorsarCommonUtils.setSafeCombo(RPCProtocol, config.getRPCProtocol());
					AutorsarCommonUtils.setSafeText(InputParameter, config.getInputPara());
					AutorsarCommonUtils.setSafeText(OutputParameter, config.getOutputPara());
					AutorsarCommonUtils.setSafeCombo(FireForgotFlag, config.getFFFlag());

					CstServer.setSelectedItems(config.getsList() != null ? config.getsList().toArray(new String[0]) : new String[0]);
					CstClient.setSelectedItems(config.getcList() != null ? config.getcList().toArray(new String[0]) : new String[0]);
		        } else {
		        	AutorsarCommonUtils.logEx("数据类型错误：" + data.getClass());
		        }
		    }
		});
	}

	private static void ServiceRPCCommonView(Composite parent, String RPCType) {
		// 创建所有 Label + Text 表单项
		String[] SpecificTypeList =  {"Event", "FireForget", "Getter", "NotificationEvent", "RequestResponse"};
		String[] RPCProtocolList =  {"TCP", "UDP"};

		serviceNameText = AutorsarCommonUtils.createLabeledReadOnly(parent, "Service Name", CurrentServiceName);
		RPCTypeText = AutorsarCommonUtils.createLabeledReadOnly(parent, "RPC Type", RPCType);
		RPCName = createLabeledText(parent, "RPC Name");
		RPCSpecificType = AutorsarCommonUtils.createLabeledCombo(parent, "RPC Specific Type", SpecificTypeList);
		RPCMethodID = AutorsarCommonUtils.createLabeledText(parent, "Method ID");
		RPCProtocol = AutorsarCommonUtils.createLabeledCombo(parent, "RPC Protocol", RPCProtocolList);
	}

	private static void AddECUsEndpointView(Composite parent) {
		String[] options = {"VechileBody", "VCC_MCU", "VCC_MPU", "TMS", "VCU", "FLZCU", "FRZCU", "RZCU", "ICC", "ICC_8155_Android", "ICC_8155_QNX",
				"TBOX", "TBOX_ex", "ADCC", "ADCC", "LCM", "FCM", "FLM", "OTA", "AdvanceService", "VDS", "TBOXPackage"};

		CstServer = new CheckableSelectText(parent, SWT.NONE, "S：", options, 2);
		serverText = CstServer.getTextControl();

		CstClient = new CheckableSelectText(parent, SWT.NONE, "C：", options, 2);
		clientText = CstClient.getTextControl();
	}

	private static Composite[] addRPCViewComposite(Composite parent) {
		// 设置主容器为一行两列的布局
		parent.setLayout(new GridLayout(2, false)); // 两列，不等宽

        // ========== 左侧服务列表区域 ==========
		Composite RPCListComposite = new Composite(parent, SWT.BORDER);
        RPCListComposite.setLayout(new GridLayout(1, false));
        GridData dataListData = new GridData(SWT.FILL, SWT.FILL, false, true);
        dataListData.widthHint = 150; // 固定宽度
        dataListData.heightHint = 400;
        RPCListComposite.setLayoutData(dataListData);
        RPCListComposite.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_WHITE));

        // ========== 右侧配置区域 ==========
        Composite RPCViewComposite = new Composite(parent, SWT.NULL);
        RPCViewComposite.setLayout(new GridLayout(1, false));
        GridData workAreaData = new GridData(SWT.FILL, SWT.FILL, true, true);
        RPCViewComposite.setLayoutData(workAreaData);
        RPCViewComposite.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
        
        // add tab composite
        CTabFolder tabFolder = new CTabFolder(RPCViewComposite, SWT.BORDER | SWT.FLAT);
	    tabFolder.setSimple(false);
	    tabFolder.setBorderVisible(false);
	    tabFolder.setTabHeight(24);

	    GridData tabFolderLayoutData = new GridData(SWT.FILL, SWT.TOP, true, false);
	    tabFolderLayoutData.heightHint = 28;
	    tabFolder.setLayoutData(tabFolderLayoutData);

	    // add rpc view composite
	    Composite RPCViewContent = new Composite(RPCViewComposite, SWT.NULL);
	    RPCViewContent.setLayout(new GridLayout(1, false));

	    GridData RPCViewContentData = new GridData(SWT.FILL, SWT.FILL, true, true);
	    RPCViewContentData.verticalIndent = 0;
	    RPCViewContent.setLayoutData(RPCViewContentData);

        return new Composite[]{RPCListComposite, tabFolder, RPCViewContent};
	}
	
	private static void addTabToFolder(CTabFolder tabFolder, String tabName, Composite dataListComposite, Composite workAreaComposite) {
        CTabItem tabItem = new CTabItem(tabFolder, SWT.NONE);
        tabItem.setText(tabName);

        if (tabFolder.getData("listener-added") == null) {
            tabFolder.addSelectionListener(new SelectionAdapter() {
                @Override
                public void widgetSelected(SelectionEvent e) {
                    CTabItem selectedTab = tabFolder.getSelection();
                    String selectedTabName = selectedTab.getText();
                    RPCListAreaCtrl(dataListComposite, selectedTabName);
                }
            });

            tabFolder.setData("listener-added", Boolean.TRUE);
        }

        // set default tab
        tabFolder.setSelection(tabFolder.getItem(0));//tabFolder.setSelection(tabFolder.getItemCount() - 1);
    }

	private static void RPCListAreaCtrl(Composite parent, String selectedTabName)
	{
		for (Control child : parent.getChildren()) {
	        child.dispose();
	    }

		AutorsarCommonUtils.logEx("enter RPCListAreaCtrl");

		if ("Event".equals(selectedTabName)) {
			// add data List button [Add, Del]
		    addServiceRPCListButton(parent);
		    // add data list table
		    addServiceRPCListTable(parent);
	    }

		parent.layout();
	}

	private static void addServiceRPCListButton(Composite parent) {
	    Composite buttonComposite = new Composite(parent, SWT.NONE);
	    RowLayout rowLayout = new RowLayout(SWT.HORIZONTAL);
	    rowLayout.spacing = 5;
	    buttonComposite.setLayout(rowLayout);

	    GridData buttonData = new GridData(SWT.FILL, SWT.TOP, true, false);
	    buttonComposite.setLayoutData(buttonData);

	    // Add 按钮
	    Button btnAdd = new Button(buttonComposite, SWT.PUSH);
	    btnAdd.setText("Add");

	    // Del 按钮
	    Button btnRemove = new Button(buttonComposite, SWT.PUSH);
	    btnRemove.setText("Del");

	    btnAdd.addSelectionListener(new SelectionAdapter() {
	        @Override
	        public void widgetSelected(SelectionEvent e) {
	        	cfmBtSt = AutorsarCommonUtils.ServiceConmfirmButtonSt.SERVICE_BT_ADD_RPC;
	        	ServiceWorkAreaCtrl(workAreaComposite, AutorsarCommonUtils.ServiceGUISet.SERVICE_GUI_EVENT);
	        	loadServiceRpcDetails(CurrentServiceName, CurrentViewPage);
	        }
	    });

	    btnRemove.addSelectionListener(new SelectionAdapter() {
	        @Override
	        public void widgetSelected(SelectionEvent e) {
	        	AutorsarCommonUtils.logEx("in addServiceRPCListButton, CurrentServiceName: " +CurrentServiceName);
				AutorsarCommonUtils.logEx("in addServiceRPCListButton, CurrentRPCType: " +CurrentRPCType);

				int selectedIndex = RPCTable.getSelectionIndex();
				AutorsarCommonUtils.logEx("in addServiceRPCListButton, selectedIndex: " +selectedIndex);

				if (selectedIndex != -1) {
					TableItem selectedItem = RPCTable.getItem(selectedIndex);
	                String RPCName = selectedItem.getText(1);  // 获取name, 在表格第一列，0是索引
	                AutorsarCommonUtils.logEx("in addServiceRPCListButton, RPCName: " +RPCName);

	                ServiceConfig serviceConfig = ConfigurationManager.getInstance().getServiceConfig();
					switch (CurrentRPCType) {
						case CurrentRPCEvent:
							boolean esuccess = serviceConfig.removeEventFromService(CurrentServiceName, RPCName);
		                    if (esuccess) {
		                        selectedItem.dispose(); // 删除表格项
		                        AutorsarCommonUtils.logEx("✅ Event 已删除：" + RPCName);
		                    } else {
		                        AutorsarCommonUtils.logEx("❌ 删除 Event 失败，未找到：" + RPCName);
		                    }
							break;
						case CurrentRPCField:
							boolean fsuccess = serviceConfig.removeFieldFromService(CurrentServiceName, RPCName);
		                    if (fsuccess) {
		                        selectedItem.dispose();
		                        AutorsarCommonUtils.logEx("✅ Field 已删除：" + RPCName);
		                    } else {
		                        AutorsarCommonUtils.logEx("❌ 删除 Field 失败，未找到：" + RPCName);
		                    }
							break;
						case CurrentRPCMethod:
							boolean msuccess = serviceConfig.removeMethodFromService(CurrentServiceName, RPCName);
		                    if (msuccess) {
		                        selectedItem.dispose();
		                        AutorsarCommonUtils.logEx("✅ Method 已删除：" + RPCName);
		                    } else {
		                        AutorsarCommonUtils.logEx("❌ 删除 Method 失败，未找到：" + RPCName);
		                    }
							break;
						default:
		                    AutorsarCommonUtils.logEx("❌ 不支持的 RPC 类型：" + CurrentRPCType);
		                    break;
					}
				}  else {
		            AutorsarCommonUtils.logEx("❌ 没有选中要删除的条目");
		        }
				//AutorsarCommonUtils.refreshTableIndex(RPCTable);
	        }
	    });
	}

	private static void addServiceRPCListTable(Composite parent) {
		// 创建表格控件
		RPCTable = new Table(parent, SWT.BORDER | SWT.FULL_SELECTION);
		RPCTable.setHeaderVisible(true);  // 显示表头
		RPCTable.setLinesVisible(true);   // 显示表格线

	    // 设置布局数据：占满父容器剩余空间
	    GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
	    RPCTable.setLayoutData(gridData);

	    // 添加两列：Index 和 ECU Name
	    TableColumn indexColumn = new TableColumn(RPCTable, SWT.NONE);
	    indexColumn.setText("Index");
	    indexColumn.setWidth(50);  // 设置宽度

	    TableColumn nameColumn = new TableColumn(RPCTable, SWT.NONE);
	    nameColumn.setText("RPC Name");
	    nameColumn.setWidth(150);  // 设置宽度
	}

	private static void ServiceConfirmButtonAdd(Composite parent) {
	    // 创建一个空的占位符，用来填充空白行，把按钮推到最下方
	    Label spacer = new Label(parent, SWT.NONE);
	    spacer.setVisible(false);
	    GridData spacerData = new GridData(SWT.FILL, SWT.FILL, true, true);
	    spacer.setLayoutData(spacerData);

	    // 按钮区域容器
	    Composite rightConfirmArea = new Composite(parent, SWT.NONE);
	    RowLayout rowLayout = new RowLayout(SWT.HORIZONTAL);
	    rowLayout.spacing = 5;
	    rightConfirmArea.setLayout(rowLayout);

	    // 设置按钮区域在父容器中的布局数据：右下对齐，不扩展
	    GridData buttonAreaData = new GridData(SWT.END, SWT.BOTTOM, false, false);
	    buttonAreaData.horizontalSpan = 2;  // 占两列
	    rightConfirmArea.setLayoutData(buttonAreaData);

	    // 添加按钮
	    confirmButton = new Button(rightConfirmArea, SWT.PUSH);
	    if (cfmBtSt == AutorsarCommonUtils.ServiceConmfirmButtonSt.SERVICE_BT_ADD_SVC) {
	    	confirmButton.setText("Add");
	    } else if (cfmBtSt == AutorsarCommonUtils.ServiceConmfirmButtonSt.SERVICE_BT_SAVE_SVC) {
	    	confirmButton.setText("Save");
	    } else if (cfmBtSt == AutorsarCommonUtils.ServiceConmfirmButtonSt.SERVICE_BT_ADD_RPC) {
	    	confirmButton.setText("Add");
	    } else if (cfmBtSt == AutorsarCommonUtils.ServiceConmfirmButtonSt.SERVICE_BT_SAVE_RPC) {
	    	confirmButton.setText("Save");
	    } else {;}

	    Button cancelButton = new Button(rightConfirmArea, SWT.PUSH);
	    cancelButton.setText("Cancel");

	    ServiceConfig serviceConfig = ConfigurationManager.getInstance().getServiceConfig();
	    confirmButton.addListener(SWT.Selection, e -> {
	        switch (CurrentViewPage) {
	            case SERVICE_GUI_LIST:
	            	if (cfmBtSt == AutorsarCommonUtils.ServiceConmfirmButtonSt.SERVICE_BT_ADD_SVC) {
	            		addServiceInstance(parent);
	            	} else if (cfmBtSt == AutorsarCommonUtils.ServiceConmfirmButtonSt.SERVICE_BT_SAVE_SVC) {
	            		 AutorsarCommonUtils.logEx("choise: \n" + CurrentServiceName);
	            		 ServiceEntry editingEntry = serviceConfig.getServiceByName(CurrentServiceName);
	            		 editingEntry.setServiceName(serviceNameText.getText());
	                     editingEntry.setServiceId(AutorsarCommonUtils.parseInteger(serviceIdText.getText(), 0));
	                     MessageDialog.openInformation(parent.getShell(), "提示", "数据已保存！");
	            	} else {AutorsarCommonUtils.logEx("cfmBtSt: \n" + cfmBtSt);}
	                break;
	            case SERVICE_GUI_EVENT:
	            	if (cfmBtSt == AutorsarCommonUtils.ServiceConmfirmButtonSt.SERVICE_BT_ADD_RPC) {
	            		// Add Event
	            		addRPCEventInstance(parent, CurrentServiceName);
	            	} else if (cfmBtSt == AutorsarCommonUtils.ServiceConmfirmButtonSt.SERVICE_BT_SAVE_RPC) {
	            		// modify Event
	            		edittingEventSave(parent);
	            	} else {
	            		AutorsarCommonUtils.logEx("cfmBtSt: \n" + cfmBtSt);
	            	}
	                break;
	            case SERVICE_GUI_FIELD:
	            	if (cfmBtSt == AutorsarCommonUtils.ServiceConmfirmButtonSt.SERVICE_BT_ADD_RPC) {
	            		addRPCFieldInstance(parent, CurrentServiceName);
	            	} else if (cfmBtSt == AutorsarCommonUtils.ServiceConmfirmButtonSt.SERVICE_BT_SAVE_RPC) {
	            		// modify Field
	            		edittingFieldSave(parent);
	            	} else {
	            		AutorsarCommonUtils.logEx("cfmBtSt: " + cfmBtSt);
	            		
	            	}
	                break;
	            case SERVICE_GUI_METHOD:
	            	if (cfmBtSt == AutorsarCommonUtils.ServiceConmfirmButtonSt.SERVICE_BT_ADD_RPC) {
	            		addRPCMethodInstance(parent, CurrentServiceName);
	            	} else if (cfmBtSt == AutorsarCommonUtils.ServiceConmfirmButtonSt.SERVICE_BT_SAVE_RPC) {
	            		// modify Method
	            		edittingMethodSave(parent);
	            	} else {
	            		AutorsarCommonUtils.logEx("cfmBtSt: " + cfmBtSt);
	            	}
	                break;
	        }
	    });
	}

	private static void edittingEventSave(Composite parent) {
		AutorsarCommonUtils.logEx("Modify Event, Service name: " +CurrentServiceName);
		String evtName = RPCName.getText().trim();
		AutorsarCommonUtils.logEx("Modify Event, Event name: " +evtName);
		AutorsarCommonUtils.logEx("Save process editingEventItem: " +editingEventItem.getEventName());
		
		/* common start */
	    String eventName       = RPCName.getText().trim();
	    String methodIdStr     = RPCMethodID.getText().trim();
		String specificType    = RPCSpecificType.getText().trim();
		String protocol        = RPCProtocol.getText().trim();
		/* cmmon end */

		/* event start */
		String eGroupName      = EventGroupName.getText().trim();
		String eGroupId        = EventGroupID.getText().trim();
		String eParameter      = EventParameter.getText().trim();
		String sStrategy       = SendStrategy.getText().trim();
		String cycTime         = CyclicTime.getText().trim();
		/* event end*/
		
		if (eventName.isEmpty() || methodIdStr.isEmpty()) {
	        AutorsarCommonUtils.logEx("❌ 请填写事件名称和 ID");
	        return;
	    }

		int eventId = 0;
		try {
			eventId = Integer.parseInt(methodIdStr);
	    } catch (NumberFormatException ex) {
	        AutorsarCommonUtils.logEx("❌ 事件 ID 必须是数字");
	        return;
	    }

		/* common start */
		editingEventItem.setEventName(eventName);
		editingEventItem.setEventId(eventId);
		editingEventItem.setRPCSpecificType(specificType);
		editingEventItem.setRPCProtocol(protocol);
		/* common end */

		/* event start */
		editingEventItem.setGroupName(eGroupName);
		editingEventItem.setGroupId(MydataTypeInterface.parseStringToInt(eGroupId));
		editingEventItem.setEventPara(eParameter);
		editingEventItem.setSendStrategy(sStrategy);
		editingEventItem.setCyclicTime(cycTime);
		/* event end */

		// 处理 sList 和 cList（多选字段）
        String[] sListArray = serverText.getText().split(", ");
        editingEventItem.setsList(new ArrayList<>(List.of(sListArray)));

        String[] cListArray = clientText.getText().split(", ");
        editingEventItem.setcList(new ArrayList<>(List.of(cListArray)));

        MessageDialog.openInformation(parent.getShell(), "提示", "数据已保存！");
	}

	private static void edittingFieldSave(Composite parent) {
		AutorsarCommonUtils.logEx("Modify Field, Service name: " +CurrentServiceName);
		String fieldName = RPCName.getText().trim();
		AutorsarCommonUtils.logEx("Modify Field, Event name: " +fieldName);
		AutorsarCommonUtils.logEx("Save process editingFieldItem: " +editingFieldItem.getFieldName());
		
		/* common start */
	    String eventName        = RPCName.getText().trim();
	    String methodIdStr      = RPCMethodID.getText().trim();
		String specificType     = RPCSpecificType.getText().trim();
		String protocol         = RPCProtocol.getText().trim();
		/* cmmon end */

		/* field start */
		//String PropertyName     = FieldPropertyName.getText().trim();
		//String PropertyDataType = FieldPropertyDataType.getText().trim();
		String GroupName        = EventGroupName.getText().trim();
		String GroupId          = EventGroupID.getText().trim();
		String EventPara        = EventParameter.getText().trim();
		boolean getterSt        = AutorsarCommonUtils.stringToBoolean(getter.getText());
		boolean setterSt        = AutorsarCommonUtils.stringToBoolean(setter.getText());
		boolean notifierSt      = AutorsarCommonUtils.stringToBoolean(notifier.getText());
		
		String getterNameText   = getterName.getText().trim();
		String getterIDText     = getterID.getText().trim();
		String getterProtText   = getterProtocol.getText().trim();
		
		String setterNameText   = setterName.getText().trim();
		String setterIDText     = setterID.getText().trim();
		String setterProtText   = setterProtocol.getText().trim();
		
		String notifierNameText = notifierName.getText().trim();
		String notifierIDText   = notifierID.getText().trim();
		String notifierProtText = notifierProtocol.getText().trim();
		/* field end*/
		
		int fieldId = 0;
		if (eventName.isEmpty() || methodIdStr.isEmpty()) {
	        AutorsarCommonUtils.logEx("❌ 请填写事件名称和 ID");
	        return;
	    }
		try {
			fieldId = Integer.parseInt(methodIdStr);
	    } catch (NumberFormatException e) {
	        AutorsarCommonUtils.logEx("❌ 事件 ID 必须是数字");
	        return;
	    }

		/* common start */
		editingFieldItem.setFieldName(eventName);
		editingFieldItem.setFieldId(fieldId);
		editingFieldItem.setRPCSpecificType(specificType);
		editingFieldItem.setRPCProtocol(protocol);
		/* common end */

		/* field start */
		//editingFieldItem.setPropertyName(PropertyName);
		//editingFieldItem.setPropertyDataType(PropertyDataType);
		editingFieldItem.setGroupName(GroupName);
		editingFieldItem.setGroupId(Integer.parseInt(GroupId));
		editingFieldItem.setEventPara(EventPara);
		editingFieldItem.setGetterStatus(getterSt);
		editingFieldItem.setSetterStatus(setterSt);
		editingFieldItem.setNotifierStatus(notifierSt);

		editingFieldItem.setGetterName(getterNameText);
		editingFieldItem.setGetterID(getterIDText);
		editingFieldItem.setGetterProtocol(getterProtText);
		editingFieldItem.setSetterName(setterNameText);
		editingFieldItem.setSetterID(setterIDText);
		editingFieldItem.setSetterProtocol(setterProtText);
		editingFieldItem.setNotifierName(notifierNameText);
		editingFieldItem.setNotifierID(notifierIDText);
		editingFieldItem.setNotifierProtocol(notifierProtText);
		/* field end */
		
		// 处理 sList 和 cList（多选字段）
        String[] sListArray = serverText.getText().split(", ");
        editingFieldItem.setsList(new ArrayList<>(List.of(sListArray)));

        String[] cListArray = clientText.getText().split(", ");
        editingFieldItem.setcList(new ArrayList<>(List.of(cListArray)));
        
        MessageDialog.openInformation(parent.getShell(), "提示", "数据已保存！");
	}

	private static void edittingMethodSave(Composite parent) {
		AutorsarCommonUtils.logEx("Modify Method, Service name: " +CurrentServiceName);
		String methodName = RPCName.getText().trim();
		AutorsarCommonUtils.logEx("Modify Method, Method name: " +methodName);
		AutorsarCommonUtils.logEx("Save process editingMethodItem: " +editingMethodItem.getMethodName());

		/* common start */
	    String eventName      = RPCName.getText().trim();
	    String methodIdStr    = RPCMethodID.getText().trim();
		String specificType   = RPCSpecificType.getText().trim();
		String protocol       = RPCProtocol.getText().trim();
		/* cmmon end */

		/* method start */
		String InputPara      = InputParameter.getText().trim();
		String OutputPara     = OutputParameter.getText().trim();
		String FFFlg          = FireForgotFlag.getText().trim();
		/* method end*/

		int methodId = 0;
		if (eventName.isEmpty() || methodIdStr.isEmpty()) {
	        AutorsarCommonUtils.logEx("❌ 请填写事件名称和 ID");
	        return;
	    }
		try {
			methodId = Integer.parseInt(methodIdStr);
	    } catch (NumberFormatException e) {
	        AutorsarCommonUtils.logEx("❌ 事件 ID 必须是数字");
	        return;
	    }

		/* common start */
		editingMethodItem.setMethodName(eventName);
		editingMethodItem.setMethodId(methodId);
		editingMethodItem.setRPCSpecificType(specificType);
		editingMethodItem.setRPCProtocol(protocol);
		/* common end */

		/* method start */
		editingMethodItem.setInputPara(InputPara);
		editingMethodItem.setOutputPara(OutputPara);
		editingMethodItem.setFFFlag(FFFlg);
		/* method end */

		// 处理 sList 和 cList（多选字段）
        String[] sListArray = serverText.getText().split(", ");
        editingMethodItem.setsList(new ArrayList<>(List.of(sListArray)));

        String[] cListArray = clientText.getText().split(", ");
        editingMethodItem.setcList(new ArrayList<>(List.of(cListArray)));

        MessageDialog.openInformation(parent.getShell(), "提示", "数据已保存！");
	}

	private static void addServiceInstance(Composite parent) {
		ServiceConfig serviceConfig = ConfigurationManager.getInstance().getServiceConfig();

		// 获取输入值
        String newServiceName = serviceNameText.getText().trim();
        String newServiceIdStr = serviceIdText.getText().trim();
        
        Shell shell = parent.getShell();

        // 校验输入
        if (newServiceName.isEmpty()) {
            MessageBox dialog = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
            dialog.setText("输入错误");
            dialog.setMessage("服务名称不能为空！");
            dialog.open();
            return;
        }

        int newServiceId;
        try {
            newServiceId = Integer.decode(newServiceIdStr);  // 支持 0x 前缀
        } catch (NumberFormatException ex) {
            MessageBox dialog = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
            dialog.setText("Input error");
            dialog.setMessage("please input a viald ID（Oct or Hex number）");
            dialog.open();
            return;
        }

        // 添加服务
        boolean success = serviceConfig.addServiceEx(newServiceName, newServiceId);
        if (success) {
            // 更新表格
            TableItem item = new TableItem(serviceTable, SWT.NONE);
            item.setText(new String[]{
                String.valueOf(serviceTable.getItemCount()),
                newServiceName
            });

            // 清空输入框
            serviceNameText.setText("");
            serviceIdText.setText("");

            // 弹出提示-取消弹框，有点烦
            //MessageBox dialog = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
            //dialog.setText("Success");
            //dialog.setMessage("Service [" + newServiceName + "] added！");
            //dialog.open();
        } else {
            MessageBox dialog = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
            dialog.setText("Fail");
            dialog.setMessage("Service [" + newServiceName + "] already exist");
            dialog.open();
        }
	}
	/* add Event to configuration (RAM) */
	private static void addRPCEventInstance(Composite parent, String serviceName) {
	    AutorsarCommonUtils.logEx("正在为服务添加事件: " + CurrentServiceName);

	    ServiceConfig serviceConfig = ConfigurationManager.getInstance().getServiceConfig();
	    ServiceEntry serviceEntry = serviceConfig.getServiceByName(CurrentServiceName);

	    if (serviceEntry == null) {
	        AutorsarCommonUtils.logEx("❌ 未找到服务: " + CurrentServiceName);
	        return;
	    }

		int eventId = 0;

		/* common start */
	    String eventName       = RPCName.getText().trim();
	    String methodIdStr     = RPCMethodID.getText().trim();
		String specificType    = RPCSpecificType.getText().trim();
		String protocol        = RPCProtocol.getText().trim();
		/* cmmon end */

		/* event start */
		String eGroupName      = EventGroupName.getText().trim();
		String eGroupId        = EventGroupID.getText().trim();
		String eParameter      = EventParameter.getText().trim();
		String sStrategy       = SendStrategy.getText().trim();
		String cycTime         = CyclicTime.getText().trim();
		/* event end*/

		if (eventName.isEmpty() || methodIdStr.isEmpty()) {
	        AutorsarCommonUtils.logEx("❌ 请填写事件名称和 ID");
	        return;
	    }

		try {
	        eventId = Integer.parseInt(methodIdStr);
	    } catch (NumberFormatException e) {
	        AutorsarCommonUtils.logEx("❌ 事件 ID 必须是数字");
	        return;
	    }

		/* common start */
	    ServiceEventConfig eventConfig = new ServiceEventConfig();
	    eventConfig.setEventName(eventName);
	    eventConfig.setEventId(eventId);
		eventConfig.setRPCSpecificType(specificType);
		eventConfig.setRPCProtocol(protocol);
		/* common end */

		/* event start */
		eventConfig.setGroupName(eGroupName);
		eventConfig.setGroupId(Integer.parseInt(eGroupId));
		eventConfig.setEventPara(eParameter);
		eventConfig.setSendStrategy(sStrategy);
		eventConfig.setCyclicTime(cycTime);
		/* event end */

		eventConfig.setRPCType(RPCTypeText.getText().trim());

		// 处理 sList 和 cList（多选字段）
        String[] sListArray = serverText.getText().split(", ");
        eventConfig.setsList(new ArrayList<>(List.of(sListArray)));

        String[] cListArray = clientText.getText().split(", ");
        eventConfig.setcList(new ArrayList<>(List.of(cListArray)));

	    boolean success = serviceConfig.addEventToService(CurrentServiceName, eventConfig);
	    if (success) {
	        AutorsarCommonUtils.logEx(" 成功添加事件 [" + eventName + "] 到服务 [" + CurrentServiceName + "]");
	    } else {
	        AutorsarCommonUtils.logEx("❌ 添加事件失败");
	    }

	    TableItem item = new TableItem(RPCTable, SWT.NONE);
	    item.setText(new String[]{
	        String.valueOf(RPCTable.getItemCount()),
	        eventName
	    });
	    item.setData(eventConfig); //绑定对象

	    // 增调试日志
	    AutorsarCommonUtils.logEx(" 新增项数据类型: " + item.getData().getClass());
	}

	/* add Method to configuration (RAM) */
	private static void addRPCFieldInstance(Composite parent, String ServiceName) {
	    AutorsarCommonUtils.logEx("正在为服务添加事件: " + CurrentServiceName);

	    ServiceConfig serviceConfig = ConfigurationManager.getInstance().getServiceConfig();
	    ServiceEntry serviceEntry = serviceConfig.getServiceByName(CurrentServiceName);

	    if (serviceEntry == null) {
	        AutorsarCommonUtils.logEx("❌ 未找到服务: " + CurrentServiceName);
	        return;
	    }
		int fieldId = 0;

		/* common start */
	    String eventName        = RPCName.getText().trim();
	    String methodIdStr      = RPCMethodID.getText().trim();
		String specificType     = RPCSpecificType.getText().trim();
		String protocol         = RPCProtocol.getText().trim();
		/* cmmon end */

		/* field start */
		//String PropertyName     = FieldPropertyName.getText().trim();
		//String PropertyDataType = FieldPropertyDataType.getText().trim();
		String GroupName        = EventGroupName.getText().trim();
		String GroupId          = EventGroupID.getText().trim();
		String EventPara        = EventParameter.getText().trim();
		boolean getterSt        = AutorsarCommonUtils.stringToBoolean(getter.getText());
		boolean setterSt        = AutorsarCommonUtils.stringToBoolean(setter.getText());
		boolean notifierSt        = AutorsarCommonUtils.stringToBoolean(notifier.getText());
		
		String getterNameText   = getterName.getText().trim();
		String getterIDText     = getterID.getText().trim();
		String getterProtText   = getterProtocol.getText().trim();
		
		String setterNameText   = setterName.getText().trim();
		String setterIDText     = setterID.getText().trim();
		String setterProtText   = setterProtocol.getText().trim();
		
		String notifierNameText = notifierName.getText().trim();
		String notifierIDText   = notifierID.getText().trim();
		String notifierProtText = notifierProtocol.getText().trim();
		/* field end*/

		if (eventName.isEmpty() || methodIdStr.isEmpty()) {
	        AutorsarCommonUtils.logEx("❌ 请填写事件名称和 ID");
	        return;
	    }
		try {
			fieldId = Integer.parseInt(methodIdStr);
	    } catch (NumberFormatException e) {
	        AutorsarCommonUtils.logEx("❌ 事件 ID 必须是数字");
	        return;
	    }

		/* common start */
	    ServiceFieldConfig fieldConfig = new ServiceFieldConfig();
	    fieldConfig.setFieldName(eventName);
	    fieldConfig.setFieldId(fieldId);
	    fieldConfig.setRPCSpecificType(specificType);
		fieldConfig.setRPCProtocol(protocol);
		/* common end */

		/* field start */
		//fieldConfig.setPropertyName(PropertyName);
		//fieldConfig.setPropertyDataType(PropertyDataType);
		fieldConfig.setGroupName(GroupName);
		fieldConfig.setGroupId(Integer.parseInt(GroupId));
		fieldConfig.setEventPara(EventPara);
		fieldConfig.setGetterStatus(getterSt);
		fieldConfig.setSetterStatus(setterSt);
		fieldConfig.setNotifierStatus(notifierSt);
		
		fieldConfig.setGetterName(getterNameText);
		fieldConfig.setGetterID(getterIDText);
		fieldConfig.setGetterProtocol(getterProtText);
		fieldConfig.setSetterName(setterNameText);
		fieldConfig.setSetterID(setterIDText);
		fieldConfig.setSetterProtocol(setterProtText);
		fieldConfig.setNotifierName(notifierNameText);
		fieldConfig.setNotifierID(notifierIDText);
		fieldConfig.setNotifierProtocol(notifierProtText);
		/* field end */

		// 处理 sList 和 cList（多选字段）
        String[] sListArray = serverText.getText().split(", ");
        fieldConfig.setsList(new ArrayList<>(List.of(sListArray)));

        String[] cListArray = clientText.getText().split(", ");
        fieldConfig.setcList(new ArrayList<>(List.of(cListArray)));
		
	    boolean success = serviceConfig.addFieldToService(CurrentServiceName, fieldConfig);
	    if (success) {
	        AutorsarCommonUtils.logEx(" 成功添加事件 [" + eventName + "] 到服务 [" + CurrentServiceName + "]");
	    } else {
	        AutorsarCommonUtils.logEx("❌ 添加事件失败");
	    }

	    TableItem item = new TableItem(RPCTable, SWT.NONE);
	    item.setText(new String[]{
	        String.valueOf(RPCTable.getItemCount()),
	        eventName
	    });
	    item.setData(fieldConfig); //绑定对象

	    // 增调试日志
	    AutorsarCommonUtils.logEx(" 新增项数据类型: " + item.getData().getClass());
	}
	
	/* add Field to configuration (RAM) */
	private static void addRPCMethodInstance(Composite parent, String ServiceName) {
		AutorsarCommonUtils.logEx("正在为服务添加事件: " + CurrentServiceName);

	    ServiceConfig serviceConfig = ConfigurationManager.getInstance().getServiceConfig();
	    ServiceEntry serviceEntry = serviceConfig.getServiceByName(CurrentServiceName);

	    if (serviceEntry == null) {
	        AutorsarCommonUtils.logEx("❌ 未找到服务: " + CurrentServiceName);
	        return;
	    }
		int methodId = 0;

		/* common start */
	    String eventName      = RPCName.getText().trim();
	    String methodIdStr    = RPCMethodID.getText().trim();
		String specificType   = RPCSpecificType.getText().trim();
		String protocol       = RPCProtocol.getText().trim();
		/* cmmon end */

		/* method start */
		String InputPara      = InputParameter.getText().trim();
		String OutputPara     = OutputParameter.getText().trim();
		String FFFlg          = FireForgotFlag.getText().trim();
		/* method end*/

		if (eventName.isEmpty() || methodIdStr.isEmpty()) {
	        AutorsarCommonUtils.logEx("❌ 请填写事件名称和 ID");
	        return;
	    }
		try {
			methodId = Integer.parseInt(methodIdStr);
	    } catch (NumberFormatException e) {
	        AutorsarCommonUtils.logEx("❌ 事件 ID 必须是数字");
	        return;
	    }

		/* common start */
	    ServiceMethodConfig methodConfig = new ServiceMethodConfig();
	    methodConfig.setMethodName(eventName);
	    methodConfig.setMethodId(methodId);
	    methodConfig.setRPCSpecificType(specificType);
	    methodConfig.setRPCProtocol(protocol);
		/* common end */

		/* method start */
	    methodConfig.setInputPara(InputPara);
	    methodConfig.setOutputPara(OutputPara);
	    methodConfig.setFFFlag(FFFlg);
		/* method end */

		// 处理 sList 和 cList（多选字段）
        String[] sListArray = serverText.getText().split(", ");
        methodConfig.setsList(new ArrayList<>(List.of(sListArray)));

        String[] cListArray = clientText.getText().split(", ");
        methodConfig.setcList(new ArrayList<>(List.of(cListArray)));

	    boolean success = serviceConfig.addMethodToService(CurrentServiceName, methodConfig);
	    if (success) {
	        AutorsarCommonUtils.logEx(" 成功添加事件 [" + eventName + "] 到服务 [" + CurrentServiceName + "]");
	    } else {
	        AutorsarCommonUtils.logEx("❌ 添加事件失败");
	    }

	    TableItem item = new TableItem(RPCTable, SWT.NONE);
	    item.setText(new String[]{
	        String.valueOf(RPCTable.getItemCount()),
	        eventName
	    });
	    item.setData(methodConfig); //绑定对象

	    // 增调试日志
	    AutorsarCommonUtils.logEx(" 新增项数据类型: " + item.getData().getClass());
	}
	
	/**
     * 辅助方法：创建带 Label 和 Text 的组合
     */
    private static Text createLabeledText(Composite parent, String labelText) {
        Label label = new Label(parent, SWT.NONE);
        label.setText(labelText);

        Text text = new Text(parent, SWT.BORDER);
        text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
        return text;
    }
	
    private static void loadExistingServiceToTable() {

    	// 1. 清空表格中的所有内容
	    if (serviceTable != null && serviceTable.getItems() != null) {
	        for (TableItem item : serviceTable.getItems()) {
	            item.dispose(); // 移除每个表项
	        }
	    }

	    // 2. 加载最新配置并更新表格
	    List<ServiceEntry> allServices = ConfigurationManager.getInstance().getServiceConfig().getAllServices();
	    for (int i = 0; i < allServices.size(); i++) {
	    	ServiceEntry entry = allServices.get(i);
	        TableItem item = new TableItem(serviceTable, SWT.NONE);
	        item.setText(0, String.valueOf(i + 1)); // 序号列，从1开始计数
	        item.setText(1, entry.getServiceName()); // 名称列
	        item.setData(entry); // 存储完整数据对象
	    }

	}

}



